const express = require('express');
const router = express.Router();

const Tab = require('../models/Tab'); // 导入Tab模型

// 获取所有标签
router.get('/', async (req, res) => {
  try {
    const tabs = await Tab.find();
    if (tabs.length === 0) {
      const newTab = new Tab({
        id: Date.now().toString(), // 使用时间戳作为唯一ID
        name: '默认标签'
      });
      await newTab.save();
      tabs.push(newTab);
    }
    res.json({ code: 0, data: tabs });
  } catch (error) {
    res.status(500).json({ code: -1, message: '服务器错误', error: error.message });
  }
});

// 获取单个标签
router.get('/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const tab = await Tab.findOne({ id });
    if (!tab) {
      return res.status(404).json({ code: -1, message: '找不到标签' });
    }
    res.json({ code: 0, data: tab });
  } catch (error) {
    res.status(500).json({ code: -1, message: '服务器错误', error: error.message });
  }
});

// 创建新标签
router.post('/', async (req, res) => {
  try {
    const { name } = req.body;

    if (!name) {
      return res.status(400).json({ code: -1, message: '标签名称是必需的' });
    }

    const newTab = new Tab({
      id: Date.now().toString(), // 使用时间戳作为唯一ID
      name
    });

    await newTab.save();
    res.status(201).json({ code: 0, data: newTab });
  } catch (error) {
    res.status(400).json({ code: -1, message: '创建标签失败', error: error.message });
  }
});

// 更新标签
router.put('/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const { name, offsetX, offsetY, scale } = req.body;

    const tab = await Tab.findOne({ id });

    if (!tab) {
      return res.status(404).json({ code: -1, message: '找不到标签' });
    }

    // 更新标签信息
    if (name !== undefined) tab.name = name;
    if (offsetX !== undefined) tab.offsetX = offsetX;
    if (offsetY !== undefined) tab.offsetY = offsetY;
    if (scale !== undefined) tab.scale = scale;

    await tab.save();
    res.json({ code: 0, data: tab });
  } catch (error) {
    res.status(400).json({ code: -1, message: '更新标签失败', error: error.message });
  }
});

// 删除标签
router.delete('/:id', async (req, res) => {
  try {
    const { id } = req.params;

    const tab = await Tab.findOneAndDelete({ id });

    if (!tab) {
      return res.status(404).json({ code: -1, message: '找不到标签' });
    }

    // 删除与该标签相关的所有卡片和连接
    const Card = require('../models/Card');
    const Connection = require('../models/Connection');
    await Card.deleteMany({ tabId: id });
    await Connection.deleteMany({ tabId: id });

    res.json({ code: 0, message: '标签和相关数据删除成功' });
  } catch (error) {
    res.status(500).json({ code: -1, message: '删除标签失败', error: error.message });
  }
});

module.exports = router;